package com.jianyun.jyzs.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.dao.UserDao;
import com.jianyun.jyzs.http.AsyTask.AsyncTaskActUtil;
import com.jianyun.jyzs.model.FriendDetailModel;
import com.jianyun.jyzs.model.imdoel.IFriendDetailModel;
import com.jianyun.jyzs.utils.FullDialogLoading;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.PathUtil;
import com.jianyun.jyzs.utils.SysConstant2;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.ShowBigImageActivity;
import com.jrmf360.rylib.common.util.ToastUtil;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yangshijun on 2018/6/4.
 * 通讯录 人员详情
 */

public class FriendDetailActivity extends AppCompatActivity {


    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.img_icon)
    SimpleDraweeView imgIcon;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_sex)
    ImageView ivSex;
    @BindView(R.id.tv_unit)
    TextView tvUnit;
    @BindView(R.id.ll_tv_name)
    TextView llTvName;
    @BindView(R.id.tv_name_value)
    TextView tvNameValue;
    @BindView(R.id.tv_department)
    TextView tvDepartment;
    @BindView(R.id.tv_department_value)
    TextView tvDepartmentValue;
    @BindView(R.id.tv_phoneNum)
    TextView tvPhoneNum;
    @BindView(R.id.tv_phoneNum_value)
    TextView tvPhoneNumValue;
    @BindView(R.id.tv_email)
    TextView tvEmail;
    @BindView(R.id.switch_btn)
    Switch switchBtn;
    @BindView(R.id.btn_sendCall)
    Button btnSendCall;
    @BindView(R.id.btn_sendSms)
    Button btnSendSms;

    private LocalBroadcastManager mLocalBroadcastManager;

    public FullDialogLoading dialog;
    private String serverUserId;
    public User user;
    private String enterpriseCode;
    private String userId;
    private UserDao userDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myfrienddetail);
        ButterKnife.bind(this);

        serverUserId = getIntent().getStringExtra("serverUserId");
        topText.setText("详细资料");
        topBack.setVisibility(View.VISIBLE);
        if (serverUserId != null && !serverUserId.equals("")) {
            try {
                initView();
            } catch (Exception e) {
                finish();
            }
        } else {
            Toast.makeText(getApplicationContext(), "用户已不存在", Toast.LENGTH_SHORT).show();
        }
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

    }



    private void initView() {
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        userDao = new UserDao(this);
        user = userDao.findUserByID(serverUserId, userId, enterpriseCode);

        //Log.i("test", "是否常用：" + isCommonContact);
        if (user != null) {
            String imgUrl = LoginCache.getInstance().getLoginCache().getErpRootUrl() + user.getServerIconPath();
            imgIcon.setImageURI(imgUrl);
            tvName.setText(user.getNameZh() == null ? user.getName() : user.getNameZh());
            tvNameValue.setText(user.getNameZh() == null ? user.getName() : user.getNameZh());
            tvUnit.setText(user.getCompany());
            tvDepartmentValue.setText(user.getDepartment());
            tvPhoneNumValue.setText(user.getPhoneNum());
            try {
                int isCommonContact = user.getIsCommonContact();
                if (isCommonContact == 1) {
                    ivSex.setImageResource(R.drawable.add_contect);
                    switchBtn.setChecked(true);
                } else {
                    ivSex.setImageResource(R.drawable.delete_contact);
                    switchBtn.setChecked(false);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        switchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked)
//                    ToastUtil.showToast(FriendDetailActivity.this, "打开");
//                else
//                    ToastUtil.showToast(FriendDetailActivity.this, "关闭");
                if (isChecked) {
                    FriendDetailModel.getInstance().addContact(enterpriseCode, userId, serverUserId,
                            new IFriendDetailModel.OnAddContactLisener() {
                                @Override
                                public void onSuccess() {
                                    user.setIsCommonContact(1);
                                    userDao.update(user);
                                    ivSex.setImageResource(R.drawable.add_contect);
                                }

                                @Override
                                public void onFailed() {
                                    ToastUtil.showToast(FriendDetailActivity.this, "常用联系人添加失败！");
                                }
                            });
                } else {
                    FriendDetailModel.getInstance().deleteContact(enterpriseCode, userId, serverUserId,
                            new IFriendDetailModel.OnDeleteContactListener() {
                                @Override
                                public void onSuccess() {
                                    user.setIsCommonContact(0);
                                    userDao.update(user);
                                    ivSex.setImageResource(R.drawable.delete_contact);
                                }

                                @Override
                                public void onFailed() {
                                    ToastUtil.showToast(FriendDetailActivity.this, "删除常用联系人失败！");
                                }
                            });
                }
            }
        });
    }

    @SuppressLint("MissingPermission")
    @OnClick({R.id.topBack, R.id.btn_sendSms, R.id.btn_sendCall, R.id.img_icon})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.topBack://返回
                finish();
                break;
            case R.id.img_icon://点击头像
                try {
//                    if (user != null && (user.getLocalIconPath() != null || user.getServerIconPath() != null)) {
//                        startActivity((new Intent(this, ShowBigImageActivity.class))
//                                .putExtra("localpath", user.getLocalIconPath())
//                                .putExtra("remotepath", LoginCache.getInstance().getLoginCache().getErpRootUrl() + user.getServerIconPath()));
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.btn_sendSms:// 发消息

                if (user == null || user.getPhoneNum() == null || user.getPhoneNum().equals("")) {
                    Toast.makeText(this, "无效的手机号码", Toast.LENGTH_LONG).show();
                    break;
                }
                Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("smsto://" + user.getPhoneNum()));
                startActivity(sendIntent);

                break;
            case R.id.btn_sendCall:// 打电话
                if (user == null || user.getPhoneNum() == null || user.getPhoneNum().equals("")) {
                    Toast.makeText(this, "无效的手机号码", Toast.LENGTH_LONG).show();
                    break;
                }
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + user.getPhoneNum()));
                startActivity(intent);
                break;

        }
    }
}
